package com.mb.search.service;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.mb.common.pojo.Product;
import com.mb.common.vo.EasyUIResult;
import com.mb.search.mapper.IndexMapper;
import org.elasticsearch.action.search.SearchRequestBuilder;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.index.query.MatchQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class SearchSercviceImpl implements SearchSercvice{

    @Autowired
    private TransportClient client;

    @Autowired(required = false)
    private IndexMapper indexMapper;

    private static final ObjectMapper mapper=new ObjectMapper();

    @Override
    public List<String> search(String query, Integer page, Integer rows) {

        MatchQueryBuilder queryBuilder = QueryBuilders.matchQuery("productName", query);

        SearchRequestBuilder requestBuilder = client.prepareSearch("sqhz");

        requestBuilder.setQuery(queryBuilder).setFrom((page-1)*rows).setSize(rows);

        SearchResponse searchResponse = requestBuilder.get();
        SearchHit[] hits = searchResponse.getHits().getHits();
        ArrayList<String> products = new ArrayList<>();
        for (SearchHit hit : hits) {
            try {
                //获取匹配到的document对象中域属性为productName的值
                String json = hit.getSourceAsString();
                //封装到集合中
                products.add(json);
            } catch (Exception e) {
                e.printStackTrace();
                continue;
            }
        }
        return products;
    }

    public List<String> find(String query) {

        ArrayList<String> values = new ArrayList<>();

        List<Product> products=indexMapper.selectProductByCategory(query);
        for (Product product : products) {
            String value = null;
            try {
                value = mapper.writeValueAsString(product);
            } catch (JsonProcessingException e) {
                e.printStackTrace();
                System.out.println("json转换异常");
            }

            values.add(value);
        }

        return values;
    }
}
